<?php
require_once 'util/class.dbservice.php';

class DiscoveryDao {
	
	 public function addDiscoveryItem($id, $type, $noteId, $picUrl, $timestamp) {
	 	try {
	 		$collection = $this->getCollection();
	 		if(!$collection)
	 			return;
	 		
	 		$collection->insert(array('_id'=>$id, 'tp'=>$type, 'nid'=>$noteId,
	 							'picUrl'=>$picUrl, 'ts'=>$timestamp));
	 	} catch(Exception $e) {
	 		syslog(LOG_ERR, "DiscoveryDao.addDiscoveryItem error, reason=".$e);
	 	}
	 }
	 
	 public function batchAddDiscoveryItems($items) {
	 	try {
	 		$collection = $this->getCollection();
	 		if(!$collection)
	 			return;
	 	
	 		$collection->batchInsert ($items);
	 	} catch(Exception $e) {
	 		syslog(LOG_ERR, "DiscoveryDao.batchAddDiscoveryItems error, reason=".$e);
	 	}
	 }
	 
	 public function getDiscoveryList($type, $pageSize, $sinceNoteId) {
	 	try {
	 		$collection = $this->getCollection();
	 		if(!$collection)
	 			return;
	 		
	 		if($sinceNoteId==0)
	 			$cursor=$collection->find(array('tp'=>$type, 'nid'=>array('$gt'=>$sinceNoteId)),
	 					array('_id'=>0, 'tp'=>0, 'ts'=>0))->sort(array('nid'=>-1))->limit($pageSize);
	 		else
		 		$cursor=$collection->find(array('tp'=>$type, 'nid'=>array('$lt'=>$sinceNoteId)),
		 				array('_id'=>0, 'tp'=>0, 'ts'=>0))->sort(array('nid'=>-1))->limit($pageSize);
	 
	 		$result=array();
	 		foreach ($cursor as $doc) {
	 			$result[]=$doc;
	 		}
			return $result;
	 
	 	} catch(Exception $e) {
	 		syslog(LOG_ERR, "DiscoveryDao.getDiscoveryList error, reason=".$e);
	 		return null;
	 	}
	 }
	 
	 private function getCollection() {
	 	$db=DBService::getGlobalDb();
	 	return $db->discovery;
	 }
}